package org.wm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.wm.constants.UserConstants;
import org.wm.entity.SysPost;
import org.wm.entity.SysUserPost;
import org.wm.exception.ServiceException;
import org.wm.mapper.SysPostMapper;
import org.wm.mapper.SysUserPostMapper;
import org.wm.service.ISysPostService;

import java.util.Arrays;
import java.util.List;

/**
 * 岗位信息 服务层处理
 * (已按照 Mybatis-Plus 混合模式进行改造)
 */
@RequiredArgsConstructor
@Service
public class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost> implements ISysPostService {

    private final SysUserPostMapper userPostMapper;

    @Override
    public IPage<SysPost> selectPostList(Page<SysPost> page, SysPost post) {
        return baseMapper.selectPostList(page, post);
    }

    @Override
    public List<SysPost> selectPostAll() {
        return baseMapper.selectPostAll();
    }

    @Override
    public List<Long> selectPostListByUserId(Long userId) {
        return baseMapper.selectPostListByUserId(userId);
    }

    @Override
    public String checkPostNameUnique(SysPost post) {
        Long postId = post.getPostId() == null ? -1L : post.getPostId();
        SysPost info = this.getOne(new LambdaQueryWrapper<SysPost>().eq(SysPost::getPostName, post.getPostName()));
        if (info != null && !info.getPostId().equals(postId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkPostCodeUnique(SysPost post) {
        Long postId = post.getPostId() == null ? -1L : post.getPostId();
        SysPost info = this.getOne(new LambdaQueryWrapper<SysPost>().eq(SysPost::getPostCode, post.getPostCode()));
        if (info != null && !info.getPostId().equals(postId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean deletePostByIds(Long[] postIds) {
        for (Long postId : postIds) {
            SysPost post = this.getById(postId);
            long count = userPostMapper.selectCount(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getPostId, postId));
            if (count > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", post.getPostName()));
            }
        }
        // 使用 ServiceImpl 提供的 removeByIds 方法
        return this.removeByIds(Arrays.asList(postIds));
    }

    @Override
    public boolean insertPost(SysPost post) {
        // 使用 ServiceImpl 提供的 save 方法
        return this.save(post);
    }

    @Override
    public boolean updatePost(SysPost post) {
        // 使用 ServiceImpl 提供的 updateById 方法
        return this.updateById(post);
    }
}